package org.wjk.controller.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.wjk.controller.service.SysMenuSvs;
import org.wjk.pojo.entity.SysMenuEntity;
import org.wjk.pojo.entity.SysUserEntity;
import org.wjk.pojo.vo.ResponseRes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*把该类的对象交给Spring，该类控制层类，返回的数据*/
/*该类时，URL统一的前缀/menu*/
@RestController
@RequestMapping("/menu")
@RequiredArgsConstructor
public class SysMenuCtrllr
{
    private final SysMenuSvs menuSvs;

    /*定义，请收前置导航守卫中请求的getUserAndHasMenus方法。返回成功响应 resMsg:"OK!"*/
    @GetMapping("/menuanduser")
    public ResponseRes getUserAndHasMenus(Authentication authentication)
    {
        System.out.println(((SysUserEntity)(authentication.getPrincipal())).getId());
        /*参数：principal里面保存即为当前登录用户信息！*/
        /*调用Svs方法查询数据库，根据当前登录用记的id获取对应的所有的拥有访问权限的菜单信息。*/
        List<SysMenuEntity> menus = menuSvs.getUserAndHasMenus(((SysUserEntity)(authentication.getPrincipal())).getId());
        Map<String, Object> currentUserAndMenus = new HashMap<>();
        currentUserAndMenus.put("currentUser", authentication.getPrincipal());
        currentUserAndMenus.put("menus", menus);
        return ResponseRes.success("ok!", currentUserAndMenus);
    }
    /*接收客户端获取所有菜单信息的方法，要求：权限：sys:menu:mngr，成功响应："OK!"*/
    @GetMapping
    @PreAuthorize("hasAuthority('sys:menu:mngr')")
    public ResponseRes getAllMenus()
    {
        return ResponseRes.success("oK!", menuSvs.getAllMenus());
    }

    @PostMapping
    public ResponseRes addNewMenu(@RequestBody SysMenuEntity menu){
        System.out.println(menu);
        menuSvs.addNewMenu(menu);
        return ResponseRes.success("ok!");
    }
}
